from django.shortcuts import render
from django.views.decorators.http import require_http_methods
from rest_framework import status
from rest_framework.permissions import IsAuthenticated, IsAdminUser, AllowAny
from rest_framework.views import APIView
from rest_framework.response import Response

from user.models import Role
from .models import DicType, DicItem
from .serializers import DicTypeSerializer, DicItemSerializer, DicItemTreeSerializer, DicTypeItemSerializer, MenuSerializer

# Create your views here.
class DicTypeView(APIView):
    # 权限控制方法
    def get_permissions(self):
        """
        根据请求方法返回不同的权限类
        """
        if self.request.method == 'GET':
            return [AllowAny()]
        elif self.request.method == 'PUT':
            return [IsAdminUser()]
        else:
            return [IsAdminUser()] # 默认需要管理员权限

    def get(self, request):
        dic_type_id = request.query_params.get('dic_type_id')
        if dic_type_id:
            dic_types = DicType.objects.filter(dic_type_id=dic_type_id)
        else:
            dic_types = DicType.objects.all()
        serializer = DicTypeSerializer(dic_types, many=True)
        return Response({'success': True, 'message': '请求成功', 'data': serializer.data}, status=status.HTTP_200_OK)
    def put(self, request):
        print('测试put请求')
        print(request.user)
        return Response({'success': False, 'message': '测试put请求', 'data': request.data}, status=status.HTTP_200_OK)

# 字典类型更新
class DicTypeUpdateView(APIView):
    permission_classes = [IsAdminUser] # 需要管理员权限
    def put(self, request):
        dic_type = request.dic_type
        serializer = DicTypeSerializer(dic_type, data=request.data, partial=True)
        if serializer.is_valid():
            serializer.save()
            return Response({'success': True, 'message': '更新成功', 'data': serializer.data}, status=status.HTTP_200_OK)
        else:
            return Response({'success': False, 'message': '更新失败', 'data': serializer.errors}, status=status.HTTP_400_BAD_REQUEST)

# 字典项
class DicItemView(APIView):
    permission_classes = [] # 无需权限限制
    def get(self, request):
        dic_type_id = request.query_params.get('dic_type_id')
        if dic_type_id:
            dic_items = DicItem.objects.filter(dic_type_id=dic_type_id)
        else:
            dic_items = DicItem.objects.all()
        serializer = DicItemSerializer(dic_items, many=True)
        return Response({'success': True, 'message': '请求成功', 'data': serializer.data}, status=status.HTTP_200_OK)

# 字典项树
class DicItemTreeView(APIView):
    permission_classes = [] # 无需权限限制
    def get(self, request):
        types = request.GET.get('types')
        # 如果没指定类别，则提示参数错误
        if not types:
            return Response({'success': False, 'message': '参数错误', 'data': []}, status=status.HTTP_400_BAD_REQUEST)
        types = types.split(',')
        # 如果指定父级字典项ID，则获取该父级字典项下的所有子字典项树
        parent_dic_item_id = request.GET.get('parent_dic_item_id')
        dic_item_trees = DicItem.objects.filter(dic_type_id__in=types, parent_dic_item_id=parent_dic_item_id)
        serializer = DicItemTreeSerializer(dic_item_trees, many=True)
        return Response({'success': True, 'message': '请求成功', 'data': serializer.data}, status=status.HTTP_200_OK)

# 字典类型及其字典项
class DicTypeItemView(APIView):
    permission_classes = [] # 无需权限限制
    def get(self, request):
        types = request.GET.get('types')
        # 如果没指定类别，则提示参数错误
        if not types:
            return Response({'success': False, 'message': '参数错误', 'data': []}, status=status.HTTP_400_BAD_REQUEST)
        types = types.split(',')
        # 获取指定类别的所有字典项
        queryset = DicType.objects.filter(dic_type_id__in=types)
        serializer = DicTypeItemSerializer(queryset, many=True)
        return Response({'success': True, 'message': '请求成功', 'data': serializer.data}, status=status.HTTP_200_OK)

# 当前用户所拥有的菜单
class AuthenticatedMenuView(APIView):
    permission_classes = [IsAuthenticated] # 需要登录权限
    def get(self, request):
        # 当前用户登录的平台
        platform_id = request.GET.get('platform_id')
        # 如果没指定平台，则提示参数错误
        if not platform_id:
            return Response({'success': False, 'message': '参数错误', 'data': []}, status=status.HTTP_400_BAD_REQUEST)
        # 获取当前用户角色
        roles = request.user.roles.all()
        if not roles:
            return Response({'success': False, 'message': '当前用户没有角色', 'data': []}, status=status.HTTP_400_BAD_REQUEST)
        # 获取当前用户拥有的菜单
        menus = []
        for role in roles:
            role_menus = role.menus.filter(platform_id=platform_id)
            menus.extend(role_menus)
        menus = list(set(menus)) # 去重
        serializer = MenuSerializer(menus, many=True)
        return Response({'success': True, 'message': '请求成功', 'data': serializer.data}, status=status.HTTP_200_OK)